package com.qigao.mall.channel.alipay;

import com.google.common.base.Charsets;
import com.qigao.mall.channel.ChannelCore;
import com.qigao.mall.channel.config.ChannelConstant;
import com.qigao.mall.commons.dto.MerChannelDto;
import com.qigao.mall.commons.enums.ChannelActionEnum;
import com.qigao.mall.commons.enums.ChannelCodeEnum;
import com.qigao.mall.commons.enums.ChannelInfoEnum;
import com.qigao.mall.commons.enums.PayProductEnum;
import com.qigao.mall.commons.param.ChannelReqParam;
import com.qigao.mall.commons.param.ChannelRespParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author luiz
 * @Title: com.qigao.mall.channel.alipay
 * @ProjectName three-mall
 * @date 2020-01-2020/1/3 17:28
 * @Description:
 * https://docs.open.alipay.com/284/h5/
 * https://docs.open.alipay.com/289/105656
 * 前端唤起支付宝APP的时候需要加前缀
 * alipays://platformapi/startapp?appId=20000067&url=后面的链接做处理
 */
@Service
public class AlipayH5AuthLogin implements ChannelCore {


    private static Logger logger= LoggerFactory.getLogger(AlipayAuthLogin.class);
    @Resource
    ChannelConstant channelConstant;

    @Override
    public boolean isSupport(PayProductEnum payProductEnum, ChannelActionEnum channelActionEnum, ChannelInfoEnum channelInfoEnum) {
        return ChannelActionEnum.PRE_LOGIN.equals(channelActionEnum) &&
                PayProductEnum.ALIPAY_WAP_WEB.equals(payProductEnum) &&
                ChannelInfoEnum.ALIPAY.equals(channelInfoEnum)
                ;
    }

    @Override
    public ChannelRespParam channelProcess(MerChannelDto merChannelDto, ChannelReqParam channelReqParam) {
        String checkTokenUrl= null;
        try {
            checkTokenUrl = channelConstant.getAlipayAuthUrl()+"?scope=auth_base,auth_user&app_id="+merChannelDto.getAppId()+"&redirect_uri="+ URLEncoder.encode(channelConstant.getAlipayAuthForwardUrl(), Charsets.UTF_8.name());
           //H5单独再做一次URLEncode
            checkTokenUrl=URLEncoder.encode(checkTokenUrl, Charsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            logger.error("[支付宝H5授权登录]异常:{}",e);
        }
        logger.info("[支付宝H5授权登录]请求地址:{}",checkTokenUrl);
        ChannelRespParam channelRespParam=new ChannelRespParam();
        channelRespParam.setRespCode(ChannelCodeEnum.SUCCESS.getCode());
        channelRespParam.setRespMsg(ChannelCodeEnum.SUCCESS.getName());
        channelRespParam.setRespContent(checkTokenUrl);
        return channelRespParam;
    }
}
